package br.com.chat.server.rmi.impl;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import br.com.chat.Message;
import br.com.chat.SenderAnswer;
import br.com.chat.User;
import br.com.chat.rmi.ChatManager;
import br.com.chat.rmi.MessageSender;
import br.com.chat.server.RemoteImpl;
import br.com.chat.utils.StringUtil;

@RemoteImpl("sender")
public class MessageSenderImpl extends UnicastRemoteObject implements MessageSender {

    public MessageSenderImpl() throws RemoteException {
        super();
    }

    private static final long serialVersionUID = 1L;

    @Override
    public SenderAnswer sendMessageToAll(User from, CharSequence content) throws RemoteException {
        if ( from == null || StringUtil.isNullOrEmpty(content) ){
            return SenderAnswer.MESSAGE_NOT_SENT;
        }
        
        return sendMessage(from, new User("TODOS"), content);
    }

    @Override
    public SenderAnswer sendMessage(User from, User to, CharSequence content) throws RemoteException {
        if ( from == null || to == null || StringUtil.isNullOrEmpty(content)){
            return SenderAnswer.MESSAGE_NOT_SENT;
        }
        
        return sendMessage(new Message(from, to, content), false);
    }

    @Override
    public SenderAnswer sendMessage(Message message) throws RemoteException {
        return sendMessage(message, true);
    }
    
    private SenderAnswer sendMessage(Message message, boolean decrypt ) throws RemoteException {
        if ( message == null || 
                message.getFrom() == null || 
                message.getTo() == null || 
                StringUtil.isNullOrEmpty(message.getContent()) ){
            return SenderAnswer.MESSAGE_NOT_SENT;
        }
        
//        if ( decrypt ){
//            try {
//                message = CryptographyMessage.decrypt(message);
//            } catch (Exception e) {
//                e.printStackTrace();
//                return SenderAnswer.MESSAGE_SENT_INTERNAL_ERROR;
//            }
//        }
        
        ChatManager manager = ChatManagerImpl.getInstance();
        
        try{
            if ( !manager.isLoggedIn(message.getFrom()) ){
                return SenderAnswer.MESSAGE_SENT_ERROR;
            }
            
            manager.publish(message);
            return SenderAnswer.MESSAGE_SENT_SUCCESSFULY;
        }
        catch (Exception e) {
            e.printStackTrace();
            return SenderAnswer.MESSAGE_SENT_INTERNAL_ERROR;
        }
    }
    

}
